//
//  XJRefreshControl.swift
//  新浪微博
//
//  Created by 徐绩 on 16/4/24.
//  Copyright © 2016年 ayumi. All rights reserved.
//

import UIKit

enum XJRefreshControlStatus: Int {

    case Normal = 0 //默认
    case Pulling     //松手刷新
    case refreshing   //刷新中

}

/// 刷新控件的高度
private let refreshVCH: CGFloat = 50

class XJRefreshControl: UIControl {
    
    var refreshStatus:XJRefreshControlStatus = .Normal {
    
        didSet{
        
            switch refreshStatus {
            
            case .Normal :
                //隐藏菊花转,箭头朝下,文字更改为等待起飞
                self.indicatorView.stopAnimating()
                self.arrowImg.hidden = false
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowImg.transform = CGAffineTransformIdentity
                })
                self.msgLabel.text = "等待起飞"
                
                if oldValue == .refreshing{
                    
                    UIView.animateWithDuration(0.25, animations: { () -> Void in
                        
                        self.tableView?.contentInset.top = self.tableView!.contentInset.top - refreshVCH
                    })
                }
                
            case .Pulling:
                //箭头朝上
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.arrowImg.transform = CGAffineTransformMakeRotation(CGFloat(M_PI))
                })
                //文字更改为松手起飞
                self.msgLabel.text = "松手起飞"
                
            case.refreshing:
                //隐藏箭头
                self.arrowImg.hidden = true
                //菊花转
                self.indicatorView.startAnimating()
                
                //文字改为正在起飞
                self.msgLabel.text = "正在起飞"
                UIView.animateWithDuration(0.25, animations: { () -> Void in
                    
                    self.tableView?.contentInset.top = self.tableView!.contentInset.top + refreshVCH
                })
                //调用刷新的方法
                sendActionsForControlEvents(.ValueChanged)
                
            }
        
        }
    }
    
    func endRefreshing(){
        refreshStatus = .Normal
    
    }

    //当前控件的父控件 homeVC->tableView->refreshControl->homeVC
   weak var tableView: UIScrollView?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }

    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    /**
     RefreshControl布局界面
     */
    private func setupUI(){
    
        self.backgroundColor = UIColor.grayColor()
        self.frame.size.height = refreshVCH
        self.frame.size.width = SCREENW
        self.frame.origin.y = -refreshVCH
        
        addSubview(arrowImg)
        addSubview(msgLabel)
        addSubview(indicatorView)
        
        arrowImg.snp_makeConstraints { (make) -> Void in
        
            make.centerX.equalTo(self).offset(-30)
            make.centerY.equalTo(self)
        }
        msgLabel.snp_makeConstraints { (make) -> Void in
            
            make.centerY.equalTo(arrowImg)
            make.leading.equalTo(arrowImg.snp_trailing)
        }
        indicatorView.snp_makeConstraints { (make) -> Void in
            
            make.center.equalTo(arrowImg)
        }
    }
    
    /**
     将要被添加到父控件上的时候调用
     */
    override func willMoveToSuperview(newSuperview: UIView?) {
        
        super.willMoveToSuperview(newSuperview)
        
        guard let tableView = newSuperview where tableView.isKindOfClass(UIScrollView.self) else{
        
            return
        }
        self.tableView = tableView as? UIScrollView
        
        //使用KVO监听tableView的contentOffset
        tableView.addObserver(self, forKeyPath: "contentOffset", options: [.New], context: nil)
    }
    
     /// 观察对象属性发生变化时调用
    override func observeValueForKeyPath(keyPath: String?, ofObject object: AnyObject?, change: [String : AnyObject]?, context: UnsafeMutablePointer<Void>) {
        
        let contentOffset = self.tableView!.contentOffset
    
        let conditionValue = -tableView!.contentInset.top - refreshVCH
        
        if tableView!.dragging {//在拖动
            
            if contentOffset.y < conditionValue && refreshStatus == .Normal{
            
                refreshStatus = .Pulling
                print("控件完全显示出来")
            }else{
            
                if contentOffset.y >= conditionValue && refreshStatus == .Pulling{
                
                    refreshStatus = .Normal
                    print("控件没有完全显示出来")
                }
            }
        
        }else{//没有拖动
        
            if refreshStatus == .Pulling{
            
                refreshStatus = .refreshing
                print("刷新中")
            }
        }
        
    }
    
    /**
     移除监听者
     */
    deinit{
        tableView?.removeObserver(self, forKeyPath: "contentOffset")
    }
    
    /**
    *  懒加载控件
    */
    //箭头
    private lazy var arrowImg: UIImageView = UIImageView(image: UIImage(named: "tableview_pull_refresh"))
    
    //提示label
    private lazy var msgLabel: UILabel = {
        
        let msgLabel = UILabel(textColor: UIColor.whiteColor(), fontSize: 13)
        msgLabel.text = "下拉刷新"
        return msgLabel
    }()
    
    //菊花
    private lazy var indicatorView: UIActivityIndicatorView = UIActivityIndicatorView()

}
